<template>
  <div class="product-detail">
    <el-row gutter="20">
      <el-col :span="12">
        <!-- 产品图片轮播 -->
        <el-carousel>
          <el-carousel-item v-for="img in product.images" :key="img">
            <img :src="img" alt="Product image" width="500" />
          </el-carousel-item>
        </el-carousel>
      </el-col>
      <el-col :span="12">
        <!-- 产品详细信息 -->
        <h2>{{ product.name }}</h2>
        <p>{{ product.description }}</p>
        <ul>
          <li v-for="(value, key) in product.specs" :key="key">{{ key }}: {{ value }}</li>
        </ul>
        <el-button type="primary" @click="addToCart">添加到购物车</el-button>
        <el-dialog v-model:visible="dialogVisible" title="提示">
          <span>{{ dialogMessage }}</span>
          <template #footer>
          <el-button @click="dialogVisible = false">确定</el-button>
        </template>
        </el-dialog>
        <router-link to="/cart">查看购物车</router-link>
      </el-col>
    </el-row>

  </div>
</template>

<script setup>
import { useCartStore } from '../stores/cartStore';
import image1 from '../assets/detail.png';
import image2 from '../assets/detail.png';
import { ref } from 'vue';
import axios from 'axios';
import { useRoute } from 'vue-router';
const route = useRoute();

// 定义产品数据
const product = ref({
  id: route.params.id,
  name: 'iPhone XS',
  description: '一款高性能的智能手机，配备了最新的处理器和摄像头技术，为您带来卓越的手机体验。',
  images: [image1, image2],
  price: 100,
  specs: {
    '颜色': '黑色',
    '尺寸': '中'
  }
});

// 添加到购物车
const dialogVisible = ref(false);
const dialogMessage = ref('');
const cartStore = useCartStore();
const addToCart = async() => {
  cartStore.addItem({
    id: product.value.id,
    name: product.value.name,
    price: product.value.price,
    quantity: 1
  });
  try {
    const response = await axios.post('http://localhost:8080/api/products/add', {
      productId: product.value.id,
      quantity: 1
    });
    dialogMessage.value = '成功添加到购物车';
  } catch (error) {
    dialogMessage.value = '添加到购物车失败';
  } finally {
    dialogVisible.value = true;
  }
};
</script>
<style>
ul,
ol {
  list-style: none;
}

.product-detail {
  margin-top: 15px;
}
</style>